package client.chat;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import client.connect.FrameConnect;

public class PanelBot extends JPanel {

	private JTextArea textArea;
	private JScrollPane scrollPane;
	private JButton button;
	
	private FrameConnect frame;

	public PanelBot(FrameConnect frame) {
		
		this.frame = frame;
		
		setBackground(Color.LIGHT_GRAY);
		setMinimumSize(new Dimension(280, 70));
		setLayout(new BorderLayout());

		textArea = new JTextArea();
		textArea.setLineWrap(true);
		textArea.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub
				if (textArea.getText().isEmpty()) {
					button.setEnabled(false);
				} else {
					button.setEnabled(true);
				}
			}

			@Override
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub

				if (button.isEnabled()
						&& e.getModifiers() == KeyEvent.CTRL_MASK
						&& e.getKeyChar() == KeyEvent.VK_ENTER) {
					int length = textArea.getText().length();
					String msg = textArea.getText().substring(0, length);
					send("me", msg);
					textArea.setText("");
					button.setEnabled(false);
				}
			}
		});
		scrollPane = new JScrollPane(textArea);
		scrollPane
				.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPane
				.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		
		scrollPane.setPreferredSize(new Dimension(210, 70));

		add(scrollPane, BorderLayout.CENTER);

		button = new JButton("Send");
		button.setEnabled(false);
		button.setPreferredSize(new Dimension(70, 70));
		button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				send("me", textArea.getText());
				textArea.setText("");
				button.setEnabled(false);
			}
		});

		add(button, BorderLayout.EAST);

		setVisible(true);
	}

	public void send(String usr, String msg) {
		
		System.out.println("the message: " + msg + " from " + usr
				+ " has been sent!");
		this.frame.client.envoyerMessage(msg);
//		this.frame.delivrerMessage(usr, msg);
	}

}
